package com.hnit.care.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hnit.care.entity.Weather;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class WeatherUtils {
    public static Weather getWeather(){

        RestTemplate restTemplate = new RestTemplate();
        Map<String,String> map = new HashMap<String,String>();
        //行政地点名:衡阳市
        map.put("district_id","430405");
        //这个是数据类型
        map.put("data_type","all");
        //百度地图应用ak
        map.put("ak","GBilns0Fvc1LQQ0mneCCy5uQrLdkHCxr");

        String res = restTemplate.getForObject(
                "https://api.map.baidu.com/weather/v1/?district_id={district_id}&data_type={data_type}&ak={ak}",
                String.class,
                map);

        JSONObject json = JSONObject.parseObject(res);

        JSONArray forecasts = json.getJSONObject("result").getJSONArray("forecasts");

        List<Weather> weathers = forecasts.toJavaList(Weather.class);

        JSONObject now = json.getJSONObject("result").getJSONObject("now");

        Weather weather = weathers.get(0);
        weather.setText_now(now.getString("text"));
        weather.setTemp(now.getString("temp"));
        return weather;
    }
}
